#!/usr/bin/python3
import click
import subprocess
import time

cases_maps = {
    'all': ['outbound1', 'outbound2', 'service-discovery1', 'service-discovery2', 'service-discovery3', 'service-discovery4', 'top-k1', 'top-k2', 'indicator1', 'indicator2', 'indicator3', 'indicator4', 'indicator5', 'indicator6'],
    'outbound': ['outbound1', 'outbound2'],
    'service-discovery': ['service-discovery1', 'service-discovery2', 'service-discovery3', 'service-discovery4'],
    'top-k': ['top-k1', 'top-k2'],
    'indicator': ['indicator1', 'indicator2', 'indicator3', 'indicator4', 'indicator5', 'indicator6'],
}

scripts_maps = {
    'outbound1': ['/usr/bin/python3', 'detection_outbound.py', 'AXSoftVM1002', 'on-box', '-no_clean'],
    'outbound2': ['/usr/bin/python3', 'detection_outbound.py', 'AXSoftVM1002', 'standalone', '-no_clean'],
    'service-discovery1': ['/usr/bin/python3', 'detection_service_discovery_port_zero_anomaly.py', 'AXSoftVM1002', 'standalone cli', '-no_clean'],
    'service-discovery2': ['/usr/bin/python3', 'detection_service_discovery_port_zero_anomaly.py', 'AXSoftVM1002', 'standalone axapi', '-no_clean'],
    'service-discovery3': ['/usr/bin/python3', 'detection_service_discovery_port_zero_anomaly.py', 'AXSoftVM1002', 'on-box cli', '-no_clean'],
    'service-discovery4': ['/usr/bin/python3', 'detection_service_discovery_port_zero_anomaly.py', 'AXSoftVM1002', 'on-box axapi', '-no_clean'],
    'top-k1': ['/usr/bin/python3', 'detection_top_k.py', 'AXSoftVM1002', 'on-box all all all all', '-no_clean'],
    'top-k2': ['/usr/bin/python3', 'detection_top_k.py', 'AXSoftVM1002', 'standalone all all all all', '-no_clean'],
    'indicator1': ['/usr/bin/python3', 'detection_indicator.py', 'AXSoftVM1002', 'on-box cli both not-test-de-escalation', '-no_clean'],
    'indicator2': ['/usr/bin/python3', 'detection_indicator.py', 'AXSoftVM1002', 'on-box cli both do-test-de-escalation', '-no_clean'],
    'indicator3': ['/usr/bin/python3', 'detection_indicator.py', 'AXSoftVM1002', 'standalone cli both not-test-de-escalation', '-no_clean'],
    'indicator4': ['/usr/bin/python3', 'detection_indicator.py', 'AXSoftVM1002', 'standalone cli both do-test-de-escalation', '-no_clean'],
    'indicator5': ['/usr/bin/python3', 'detection_indicator.py', 'AXSoftVM1002', 'standalone cli detection-window-size-1 not-test-de-escalation', '-no_clean'],
    'indicator6': ['/usr/bin/python3', 'detection_indicator.py', 'AXSoftVM1002', 'standalone cli detection-window-size-1 do-test-de-escalation', '-no_clean'],
}

def run_script(script_name):
    log_file_name = '/var/log/ddos/%s-%s.log' % (script_name, time.strftime('%Y%m%d%H%M%S', time.localtime()))
    # 打开一个日志文件，用于记录输出
    with open(log_file_name, "w") as log_file:
        # 启动子进程，执行Python脚本
        process = subprocess.Popen(scripts_maps[script_name],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT,
                                universal_newlines=True)
        
        # 循环读取子进程的输出
        for line in process.stdout:
            # 实时打印输出
            print(line, end="")
            # 将输出写入日志文件
            log_file.write(line)

        # 等待子进程完成
        process.wait()
    log_file.close()
    return log_file_name



def parse_log(log_file, case_log_name):
    tag = False
    with open(log_file, "r") as log_file:
        for line in log_file:
            if '======RESULTS COUNTS SUMMARY======' in line:
                tag = True
            if tag:
                with open(case_log_name, 'a') as results_file:
                    results_file.write(line)

def compare_log(log_file1, log_file2):
    with open(log_file1, "r") as log_file1:
        with open(log_file2, "r") as log_file2:
            for line1 in log_file1:
                if 'Pass:' in line1:
                    pass_count1 = line1.split('Pass:')[1].split('Fail:')[0].strip()
                    fail_count1 = line1.split('Fail:')[1].split('Skip:')[0].strip()
                    skip_count1 = line1.split('Skip:')[1].split('Total:')[0].strip()
                    total_count1 = line1.split('Total:')[1].strip()
                    break
            for line2 in log_file2:
                if 'Pass:' in line1:
                    pass_count2 = line2.split('Pass:')[1].split('Fail:')[0].strip()
                    fail_count2 = line2.split('Fail:')[1].split('Skip:')[0].strip()
                    skip_count2 = line2.split('Skip:')[1].split('Total:')[0].strip()
                    total_count2 = line2.split('Total:')[1].strip()
                    break
            if pass_count1 == pass_count2 and fail_count1 == fail_count2 and skip_count1 == skip_count2 and total_count1 == total_count2:
                print('两个日志文件的结果一致')
            if fail_count1 != 0 or fail_count2 != 0:
                fail_logs1 = []
                fail_logs2 = []
                for line1 in log_file1:
                    if line1.endswith('--- fail'):
                        fail_logs1.append(line1[20:])
                for line2 in log_file2:
                    if line2.endswith('--- fail'):
                        fail_logs2.append(line2[20:])
                log1_fail = []
                log2_fail = []
                for fail_log1 in fail_logs1:
                    if fail_log1 not in fail_logs2:
                        log1_fail.append(fail_log1)
                for fail_log2 in fail_logs2:
                    if fail_log2 not in fail_logs1:
                        log2_fail.append(fail_log2)
                if len(log1_fail) == 0 and len(log2_fail) == 0:
                    print('两个日志文件的结果一致')
                else:
                    print('两个日志文件的结果不一致')
                    print('只在第一个日志文件中出现的失败用例：')
                    for log1 in log1_fail:
                        print(log1)
                    print('只在第二个日志文件中出现的失败用例：')
                    for log2 in log2_fail:
                        print(log2)

@click.group()
def main():
    pass

# 定义 "upgrade" 命令
@click.command()
def upgrade_AX():
    click.echo("正在升级 AX1/AX2...\n")
    # 实现升级 AX 的代码

# 定义 "compare" 命令
@click.command()
def compare(log_file1, log_file2):
    click.echo("正在比较 %s和%s...\n" % (log_file1, log_file2))
    compare_log(log_file1, log_file2)

# 定义 "run" 命令
@click.command()
@click.option('-c', '--case', type=click.Choice(['all', 'outbound', 'service-discovery', 'top-k', 'indicator', 'continuous-learning']), default='all')
def run(case):
    case_log_name = '/var/log/ddos/results-%s-%s.log' % (case, time.strftime('%Y%m%d%H%M%S', time.localtime()))
    for script_name in cases_maps[case]:
        log_name = run_script(script_name)
        parse_log(log_name, case_log_name)

# 将 "run" 命令组添加到最外层命令
main.add_command(run)
# 将 "upgrade" 命令添加到最外层命令
main.add_command(upgrade_AX)

if __name__ == '__main__':
    main()